package middlewares

import (
	"HeadLineNews/pkg/db/cache"
	"HeadLineNews/pkg/zaplog"
	"HeadLineNews/resp"
	"HeadLineNews/utils/gin_ctx"
	"github.com/gin-gonic/gin"
)

func PermissionRequired(c *gin.Context) {
	userId := c.GetString(gin_ctx.UserId)
	if userId == "0" { // 最高管理员，拥有全部权限
		c.Next()
		return
	}
	userGroupIds := c.GetStringSlice(gin_ctx.UserGroupIds)
	if len(userGroupIds) == 0 { // 不在任何群组内
		zaplog.L().Warn("permission refused", zaplog.Fields(c, nil, nil)...)
		resp.PermissionDenied(c)
		c.Abort()
		return
	}
	// 查询群组信息
	groupPerms, err := cache.GetGroupPerms(userGroupIds...)
	if err != nil {
		zaplog.L().Error("query group perms failed", zaplog.Fields(c, userGroupIds, err)...)
		resp.ServerBusy(c)
		c.Abort()
		return
	}

	for _, perm := range groupPerms {
		if c.FullPath() == perm { // 遍历权限
			c.Next()
			return
		}
	}
	// 走到这里说明没有一条权限是当前用户有的
	zaplog.L().Warn("permission refused", zaplog.Fields(c, nil, nil)...)
	resp.PermissionDenied(c)
	c.Abort()
	return
}
